package book;

import Constant.constant;
import utils.AnalyzingBook;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    private Book[] books;//定义书籍对象books
    private int bookCount;//所有图书个数
    public int getBookCount() {
        return bookCount;
    }
    Scanner scanner = new Scanner(System.in);
    private static Library instance;

    private Library() {
        loadBook();
    }

    public static Library getInstance(){
        if(instance == null) {
            instance = new Library();
        }
        return instance;//饿汉式
    }
    AnalyzingBook analyzingBook = new AnalyzingBook();
    private void loadBook() {
        try {
            //加载读取文件内容
            Book[] allBook = analyzingBook.loadBook(constant.FILE_NAME);
            //默认图书容量为5
            books = new Book[constant.CAPACITY];
            //判断是否含有数据
            if(allBook == null) {
                bookCount = 0;
            }else {
                //获得实际有多少书籍,是否超出容量
                if(books.length < allBook.length) {
                    books = new Book[allBook.length];//按照情况重新分配数组内存
                }
                //将书籍放入图书馆中books中
                for (int i = 0; i < allBook.length; i++) {
                    books[i] = allBook[i];
                }
                bookCount = allBook.length;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //将内存中的书籍数组进行存储到文件中
    private void storeBook() {
        try {
            analyzingBook.storeBook(books,constant.FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //---------------共同操作------------------
    //查找书籍
    public void searchBook(){
        System.out.println("请输入要查找的书名：");
        String title = scanner.nextLine();
        Book book = searchBook(title);
        //TODO:可以实现通过关键字来查找书籍
        if(book == null) {
            System.out.println("没有找到你要查找的图书...");
        }else {
            System.out.println(book);
        }
    }
    private Book searchBook(String title){
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getTitle().equals(title)) {
                return book;
            }
        }
        return null;
    }
    //显示书籍
    public void displayBook() {
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }
    //退出系统
    public void exitBookSystem() {
        System.exit(0);
        System.out.println("成功退出系统");
    }
    //---------------管理员操作------------------
    public void addBook(Book newBook) {
        loadBook();//加载数据，确保每次都能是最新数据
        if(bookCount >= books.length) {
            System.out.println("图书馆已满，无法上架书籍");
            //TODO:可以考虑进行扩容图书馆
            return;
        }

        books[bookCount] = newBook;
        //最大ID的
        if(bookCount != 0) {
            Book bookLastID = books[bookCount - 1];
            newBook.setNumber(bookLastID.getNumber()+1);
        }else {
            newBook.setNumber(1);
        }
        bookCount++;
        storeBook();//存储到文件中
        System.out.println("图书："+newBook.getTitle()+"上架成功！");//打印日志
    }
    public void updateBook(Book book) {
        loadBook();
        int index = searchBookIDReturnIndex(book.getNumber());
        books[index] = book;//将更新好的书籍覆盖原来这个下标的书籍
        storeBook();//进行存储
    }
    //通过书籍ID查找书籍，返回书籍对象对应的数组下标
    private int searchBookIDReturnIndex(int ID) {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getNumber() == ID) {
                return i;
            }
        }
        return -1;
    }
    //通过书籍ID查找书籍，返回书籍对象
    public Book searchBookID(int number){
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getNumber() == number) {
                return books[i];
            }
        }
        return null;
    }
    //删除书籍
    public void removeBook(int number) {
        loadBook();
        int index = searchBookIDReturnIndex(number);
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i+1];//将后面的数组元素给到前一个
        }
        books[bookCount-1] = null;//将最后一个元素设为null
        storeBook();
        bookCount--;//书本数量减少一个
    }
    //统计每本书的借阅次数
    public void borrowCount() {
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i].getTitle()+"一共借阅了"+books[i].getBorrowCount()+"次！");
        }
    }
    //查询最受欢迎的前n本书
    public void mostlikeBook(int n) {
        loadBook();
        //排序时，不能改变原来数组顺序
        Book[] temp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            temp[i] = books[i];
        }
        //将临时数组按照借阅次数进行排序
        Arrays.sort(temp);
        //输出受欢迎的前n本书的信息
        for (int i = 0; i < n; i++) {
            System.out.println(("索引: "+i+" 书名："+ temp[i].getTitle()+" 作者："+ temp[i].getTitle()+" 借阅次数："+temp[i].getBorrowCount()));
        }

    }
    //查看库存状态
    public void checkInventoryStatus() {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            String status;
            if(books[i].isBorrowed()) {
                status = "已经借出！";
            }else status = "还在图书馆中！";
            System.out.println("图书："+books[i].getTitle()+",目前状态："+status);
        }
    }
    //并移除上架超过⼀年的图书
    public void checkAndRemoveOldBook(Scanner scanner) {
        loadBook();
        //获得当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        //将当前时间戳转换为LocalDateTime类型
        LocalDateTime currentDate = Instant.ofEpochMilli(currentTimestamp).atZone(ZoneId.systemDefault()).toLocalDateTime();
        boolean flag = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            LocalDateTime shelfDate = book.getShelfDate();
            long betweenTime = ChronoUnit.YEARS.between(shelfDate,currentDate);
            if(betweenTime >= 1) {
                System.out.println(book.getTitle()+"已经上架超过一年了，是否删除？(请输入yes或者no)");
                scanner.nextLine();
                if (scanner.nextLine().equals("yes")) {
                    //调用removeBook()方法，删除书籍
                    removeBook(book.getNumber());//参数是书籍对应的ID
                    i--;
                }
                flag = true;
                System.out.println(book.getTitle()+"删除成功！");
            }
        }
        if(!flag) {
            System.out.println("没有超过上架一年的书籍!");
        }
        storeBook();
    }


    //---------------普通用户操作------------------
    //借阅图书
    public void borrowBook(int bookID) {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getNumber() == bookID) {
                book.setBorrowed(true);
                book.increaseBorrowCount();
                break;
            }
        }
        storeBook();
    }
    //归还图书
    public void returnBook(int bookID) {
        loadBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getNumber() == bookID) {
                book.setBorrowed(false);
            }
        }
        storeBook();
    }
    //查看个人借阅情况
    public void viewBorrowBook() {

    }
}
